package com.yjy.fuyao.message.event;
import com.alibaba.fastjson.JSONObject;
import com.yjy.fuyao.message.entity.Event;
import com.yjy.fuyao.message.entity.Message;
import com.yjy.fuyao.message.service.MessageService;
import com.yjy.fuyao.message.util.MessageConstant;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Component
public class EventConsumer implements MessageConstant {

    @Resource
    private MessageService messageService;

    @KafkaListener(topics = "system")
    public void processMessage(ConsumerRecord record) {
        System.out.println("消费者开始消费...");
        Event event = JSONObject.parseObject(record.value().toString(), Event.class);
        Message message = new Message();
        message.setFromId(SYSTEM_USER_ID);
        message.setToId(event.getEntityUserId());
        message.setTopic(event.getTopic());
        message.setStatus(1);
        message.setCreateTime(LocalDateTime.now());
        Map<String, Object> content = new HashMap<>();
        content.put("userId", event.getUserId());
        content.put("entityType", event.getEntityType());
        content.put("entityId", event.getEntityId());

        if (!event.getData().isEmpty()) {
            for (Map.Entry<String, Object> entry : event.getData().entrySet()) {
                content.put(entry.getKey(), entry.getValue());
            }
        }

        message.setContent(JSONObject.toJSONString(content));

        messageService.save(message);


    }

}
